import React from 'react';
import { SwipeAction, Tabs, Accordion, List, Icon, SearchBar, Toast, Tools, Result, ActivityIndicator } from 'weaver-mobile';
import { SearchPage, Browser } from 'weaver-mobile-page';


import { observer, inject } from 'mobx-react';
import { toJS } from 'mobx';
import { withRouter } from 'react-router-dom';
import ComWorkFlow from './ComWorkflow'
import * as EmSDK from '../../util/emSDK';
import { forwardViewForm, transQueryParams,forwardViewPage } from '../../util/common';



const getLabel = Tools.getLabel;
const template = {
    default: [
        {
            key: 'col1',
            configs: [
                {
                    key: 'col1_row1',
                    configs: [
                        { key: 'name' },
                    ],
                },
            ],
        },
    ],
};

@inject("wfworkflowAddStore")
@withRouter
@observer
class AddList extends React.Component {


    componentWillMount() {
        const { location = {}, wfworkflowAddStore } = this.props;
        const { inintDatas, setState } = wfworkflowAddStore;
        const queryParams = transQueryParams(location);
        setState({ queryParams })
        let isRetainCondition = 0;
        if (queryParams.hasOwnProperty("retainCondition")) {
            isRetainCondition = 1;
        } else {
            window.sessionStorage && sessionStorage.removeItem("__wf__list__add__retainCondition");
        }
        inintDatas(isRetainCondition);
    }
    componentDidMount() {
        const { location } = this.props;
        const { searchPage } = this.props.wfworkflowAddStore;
        searchPage.setState({ template, placeholder: getLabel(391111, "请输入路径名称/首字母/id") });
        let data = Tools.ss.getJSONObj("wfAgentListData")
        searchPage.list.setState({ data: data || [] });
        EmSDK.setEmTopNav(location.pathname);
    }

    componentWillUpdate(nextProps) {
        const { location, wfworkflowAddStore } = nextProps;
        const { pathname = "" } = location;

        const { browserStore } = wfworkflowAddStore;
        if (this.props.location.pathname !== pathname) {
            if (pathname === "/add") {
                EmSDK.controlEmTopNav({ title: getLabel(16392, "新建流程"), showCloseButton: true })
            } else if (pathname === "/add/importWf") {
                EmSDK.controlEmTopNav({ title: getLabel(391112, "选择导入流程"), showCloseButton: false })
            }
        }
    }
    /**
     * 
     * @param {收藏还是取消收藏} type 
     * @param {workflowtype} typeid 
     * @param {wfid} wfid 
     */
    doColl(type, typeid, wfid) {
        const { wfworkflowAddStore } = this.props;
        wfworkflowAddStore.doAddWfToColl(type, typeid, wfid)
    }


    /**
     * 跳转到新建流程
     */
    doLinktoAddRequest(ev, item) {
        const { wfworkflowAddStore } = this.props;
        const { resultDatas, setSS, queryParams, openByDefaultBrowser } = wfworkflowAddStore;
        let urlParams = { ...resultDatas, ...{ iscreate: 1, workflowid: item.id } };
        if(openByDefaultBrowser==1){
            urlParams.openByDefaultBrowser=openByDefaultBrowser;
        }
        if (queryParams.hasOwnProperty("src") && queryParams.src === "meeting") {
            //检测到设备是ios的时候才编码
            if ((/OS [\d._]+/gi).test(window.navigator.userAgent)) {
                for (let key in queryParams) {
                    if (key.includes("field")) {
                        queryParams[key] = encodeURIComponent(queryParams[key])
                    }
                }
            }
            urlParams = { ...urlParams, ...queryParams }
        }
        setSS();
        if(parseInt(item.id,0) <= 0){
            forwardViewPage(item.mobileurl);
        }else{
            forwardViewForm(urlParams);
        }
    }


    /** 
     * 常用流程 1
     * 我的收藏 2
     * 全部流程 3
     */
    createListItem(type) {
        const { wfworkflowAddStore, history } = this.props;
        const { dialogSwitch1, dialogSwitch2, datasM=[], datas=[], activeKey2, activeKey3, isFuzzy, searchPage, browserStore, queryParams, loading } = wfworkflowAddStore;
        let data;

        let wftypes = [];
        if (type === 2) {
            data = datas;
        } else {
            if (isFuzzy) {
                if (toJS(searchPage.searchValue) === "") {
                    data = datas;
                } else {
                    data = datasM;
                }
            } else {
                data = datas;
            }
        }
        for (const d of toJS(data)) {
            let wfbeans = [];
            for (const wfbean of d.wfbeans) {
                if (type === 2 && wfbean.wfColl !== '1') { continue; }
                let isShowImport = false;
                let isShowSelectcreatorIdentity = false;
                if (wfbean.isImportWf === "1") {
                    isShowImport = true;
                }
                if (wfbean.belongtoUsers.length > 0 || wfbean.beagenters.length > 0) {
                    isShowSelectcreatorIdentity = true;
                }
                wfbeans.push(
                    <SwipeAction
                        autoClose
                        key={wfbean.id}
                        right={(queryParams.src && queryParams.src === "meeting") ? [] : [
                            {
                                text: parseInt(wfbean.wfColl, 10) === 1 ? getLabel(129753, '取消收藏') : getLabel(22255, '添加收藏'),
                                onPress: () => {
                                    this.doColl(parseInt(wfbean.wfColl, 10) === 1 ? "0" : "1", d.id, wfbean.id);
                                },
                                className: parseInt(wfbean.wfColl, 10) === 1 ? "quxiao" : "tianjia",
                            },
                        ]}
                    >
                        <List.Item
                            extra={
                                (isShowSelectcreatorIdentity || isShowImport) ?
                                    <div className="wrap-extra-icon-com">
                                        <div className="extra-icon-com" style={{ display: ((isShowImport || isShowSelectcreatorIdentity) && !(isShowImport && isShowSelectcreatorIdentity)) ? "block" : "none" }}>{/*占位div */} </div>
                                        <div className="extra-icon-com"//导入流程
                                            style={{ display: isShowImport ? "block" : "none", }}
                                            onClick={() => {
                                                const { setState } = this.props.wfworkflowAddStore;
                                                setState({ selectData: wfbean });
                                                history.push(browserStore.path);
                                            }}
                                        >
                                            {isShowImport && <Icon type="download" size="xs"></Icon>}
                                        </div>
                                        <div className="extra-icon-com"//身份选择
                                            style={{ display: isShowSelectcreatorIdentity ? "block" : "none", }}
                                            onClick={() => {
                                                const { setState } = this.props.wfworkflowAddStore;
                                                let parentURL = window.location.href;
                                                if (parentURL.indexOf("/spa") > -1) {
                                                    parentURL = parentURL.substr(parentURL.indexOf("/spa"));
                                                }
                                                setState({ selectData: wfbean, parentURL: parentURL });
                                                this.props.history.push({
                                                    pathname: "/creatorIdentity"
                                                })
                                            }}>
                                            {isShowSelectcreatorIdentity && <Icon type="switch-o" size="xs"></Icon>}
                                        </div>

                                    </div> : undefined
                            }
                        >
                            <div className='item-name' onClick={(e) => { this.doLinktoAddRequest(e, wfbean); }}>
                                {wfbean.name}
                            </div>
                        </List.Item></SwipeAction>
                );
            }
            if (type === 2 && wfbeans.length === 0) { continue; }
            if (wfbeans.length === 0) { continue; }

            wftypes.push(
                <Accordion.Panel
                    key={d.id}
                    showArrow={false}
                    header={<div className="judgeTest">{
                        <Icon type={
                            type === 2 ? (dialogSwitch1.get(d.id) ? 'take-up' : 'open') : (dialogSwitch2.get(d.id) ? 'take-up' : 'open')
                        } size='xxs'></Icon>}{d.typeName} ({wfbeans.length})</div>
                    }
                >
                    <List arrow=''
                        className="my-list">
                        {wfbeans}
                    </List>
                </Accordion.Panel>
            );
        }
        let total = <Accordion
            accordion={false}
            activeKey={type === 2 ? toJS(activeKey2) : toJS(activeKey3)}
            className="my-accordion"
            onChange={(key) => {
                const { wfworkflowAddStore } = this.props;
                const { changeAccordionIcon } = wfworkflowAddStore;
                changeAccordionIcon(key, "true", type)
            }}  >
            {wftypes.map(item => {
                return item
            })}
        </Accordion>
        if (wftypes.length > 0) {
            return total;
        } else {
            // return (<div className="wf-add-NoData" >{getLabel(83553, "暂无数据")}</div>)
            return loading ? <div></div> : (this.getNoDataPage())
        }

    }

    getNoDataPage = () => {
        return (
            <div style={{ width: "100%", height: "100%" }} className="wf-add-NoData">
                <Result
                    img={<Icon type="no-data" size="lg" />}
                    message={getLabel(83553, "暂无数据")}
                />
            </div>
        )
    }


    getTabDom = () => {
        const { wfworkflowAddStore, location } = this.props;
        let { datas, tabs, isHasCom, hasTab, queryParams = {} } = wfworkflowAddStore;
        if (queryParams.hasOwnProperty("isNeedTab")) {
            queryParams.isNeedTab == 1 ? hasTab = true : hasTab = false;
        }
        let dom;
        if (wfworkflowAddStore.page > -1) {//使用不同page渲染两次Tabs组件，会定位不到实际的tab上
            if (!hasTab) {
                dom = (
                    <div className="wf-add-noTabs-wrap">
                        <div className="wf_add_judgeHeight wf_add_content ">
                            <div className="wf_add_wrap">
                                <div className=" wf_add_judgePl">
                                    {this.createListItem(3)}
                                </div>
                            </div>
                        </div>
                    </div>
                )
            } else {
                if (isHasCom === "1") {
                    dom = (< Tabs tabs={toJS(tabs)}
                        animated={false}
                        page={wfworkflowAddStore.page}
                        // renderTabBar={props => <Tabs.DefaultTabBar {...props} tabs={toJS(tabs)} page={2.4} >{tabs.title}</Tabs.DefaultTabBar>}
                        onTabClick={(tabm) => {
                            let tab = toJS(tabm);
                            const { setState, searchPage, activeKey2, activeKey3, changeAccordionIcon, saveLastSet } = wfworkflowAddStore;
                            setState({ "page": parseInt(tab.sub, 10) - 1, "activeKey3": [], activeKey2: [] })
                            searchPage.setState({ searchValue: '' });
                            changeAccordionIcon(activeKey3, "", 3)
                            changeAccordionIcon(activeKey2, "", 2)
                            saveLastSet({ wfDefaultSelectedTabKey: tab.wfDefaultSelectedTabKey })
                        }}
                    >
                        <div className="wf_add_content">
                            <div className="wf_add_wrap">
                                <div className="wf_add_wrap_content">
                                    <ComWorkFlow datas={datas} />
                                </div>
                            </div>
                        </div>
                        <div className="wf_add_content">
                            <div className="wf_add_wrap">
                                <div className=" wf_add_judgePl">
                                    {this.createListItem(2)}
                                </div>
                            </div>
                        </div>
                        <div className="wf_add_judgeHeight wf_add_content ">
                            <div className="wf_add_wrap">
                                <div className=" wf_add_judgePl">
                                    {this.createListItem(3)}
                                </div>
                            </div>
                        </div>
                    </Tabs>)
                } else {
                    dom = (< Tabs tabs={toJS(tabs)}
                        animated={false}
                        page={wfworkflowAddStore.page}
                        onTabClick={(tabm) => {
                            let tab = toJS(tabm);
                            const { setState, searchPage, activeKey3, activeKey2, changeAccordionIcon, saveLastSet } = wfworkflowAddStore;
                            setState({ page: parseInt(tab.sub, 10) - 1, activeKey3: [], activeKey2: [] })
                            searchPage.setState({ searchValue: '' });
                            changeAccordionIcon(activeKey3, "", 3)
                            changeAccordionIcon(activeKey2, "", 2)
                            saveLastSet({ wfDefaultSelectedTabKey: tab.wfDefaultSelectedTabKey })
                        }}
                    >
                        <div className="wf_add_content">
                            <div className="wf_add_wrap">
                                <div className=" wf_add_judgePl">
                                    {this.createListItem(2)}
                                </div>
                            </div>
                        </div>
                        <div className="wf_add_judgeHeight wf_add_content ">
                            <div className="wf_add_wrap">
                                <div className=" wf_add_judgePl">
                                    {this.createListItem(3)}
                                </div>
                            </div>
                        </div>
                    </Tabs >)
                }
            }
        }

        return dom
    }

    /** 导入流程 */
    getDisplayCom() {
        const { wfworkflowAddStore } = this.props;
        const { browserStore, selectData=[], currentUser = {} } = wfworkflowAddStore;
        return (
            <div style={{ 'display': 'none' }}>
                <Browser
                    label={getLabel(131692, "流程")}
                    store={browserStore}
                    hasAdvanceSerach
                    type={16}
                    conditionDataParams={{ importWfBrow: "1", workflowid: toJS(selectData).id, newReq: '1', ismobile: '1' }}
                    dataParams={
                        {
                            importWfBrow: "1",
                            formid: selectData.formid,
                            isbill: selectData.isbill,
                            workflowid: toJS(selectData).id,
                            creater: currentUser.id || ''
                        }}
                    searchBarProps={{
                        placeholder: getLabel(391113, '请输入流程标题')
                    }}
                    onOk={(ids, namespan, datas, datasMore) => {
                        const { requestImport, resultDatas, selectData } = this.props.wfworkflowAddStore;
                        if (datas.length > 0) {
                            let resultDatas_1 = toJS(resultDatas);
                            let selectData_1 = toJS(selectData);
                            let requestname_arr = []
                            let ids_arr = ids.split(",");
                            ids_arr.map(id => {
                                datasMore.map(item => {
                                    if (id == item.id) {
                                        requestname_arr.push(item.requestname)
                                    }
                                })
                            })
                            const importParams = {
                                src: "import",
                                imprequestid: ids,
                                workflowid: selectData_1.id,
                                isagent: resultDatas_1.isagent,
                                beagenter: resultDatas_1.beagenter,
                                requestname: requestname_arr.join(","),
                            };
                            requestImport(importParams)
                        } else {
                            Toast.info(getLabel(84093, '请至少选择一条记录!'), 2);
                        }
                    }}
                    isSingle={true}
                />
            </div>
        )
    }



    render() {

        const { wfworkflowAddStore, location } = this.props;
        const { pathname } = location;
        const { searchPage, isHasCom, loading = false } = wfworkflowAddStore;
        return <div className="wf_add" style={{ display: (pathname === "/add/searchRecord" || pathname === "/add/importWf") ? "none" : "block" }}>
            <div style={{ height: "100%" }}>
                <div>
                    <SearchBar
                        placeholder={getLabel(391111, "请输入路径名称/首字母/id")}
                        value={searchPage.searchValue}
                        onFocus={() => {
                            const { history } = this.props;
                            history.push(searchPage.path);
                        }}
                    />
                    <SearchPage
                        store={searchPage}
                        type={1}
                        nameKey="name"
                        rowKey="key"
                        template={template}
                        onClear={e => {
                            const { searchPage } = this.props.wfworkflowAddStore;
                            const { list } = searchPage;
                            list.setState({ data: [] });
                        }}
                        onSubmit={(e) => {
                            const { setState, datas, changeAccordionIcon, activeKey3, searchPage } = this.props.wfworkflowAddStore;
                            let fu, fu2;
                            if (toJS(e).name) {
                                fu = toJS(e).name.toUpperCase();
                                fu2 = toJS(e).name;
                            } else {
                                fu = e.toUpperCase();
                                fu2 = e;
                            }
                            if (isHasCom === "1") {
                                setState({ page: 2 })
                            } else {
                                setState({ page: 1 })
                            }
                            if (fu === "") {
                                changeAccordionIcon(activeKey3, "", 3)
                                setState({ isFuzzy: false, activeKey3: [] })
                            } else {
                                setState({ isFuzzy: true })
                                //刷新模糊搜索的数据
                                let types = [];
                                toJS(datas).map(item => {
                                    let wfbeans = [];
                                    item.wfbeans.map(wfbean => {
                                        if (wfbean.name.toUpperCase().includes(fu) || wfbean.id.toUpperCase().includes(fu) || wfbean.spell.toUpperCase().includes(fu)) {
                                            wfbeans.push(wfbean);
                                        }
                                        return wfbeans;
                                    })
                                    if (wfbeans.length > 0) {
                                        item.wfbeans = wfbeans;
                                        types.push(item);
                                    }
                                    return types;
                                })
                                let activeKey1 = [];
                                types.map(items => {
                                    return activeKey1.push(items.id);
                                })
                                setState({ searchValue: fu, searchValue_default: fu2 });
                                changeAccordionIcon(activeKey1, "true", 3)
                                setState({ datasM: types, activeKey3: activeKey1 });

                                //保存搜索历史
                                let arr = toJS(searchPage.list.data);
                                if (arr.length <= 0) {
                                    arr.push({ name: fu2, key: "0" })
                                } else {
                                    let index = -1;
                                    let flag = false;//输入的e是否已在记录中
                                    arr.map(item => {
                                        if (item.name === fu2) {
                                            flag = true;
                                            index = parseInt(item.key, 10);
                                        }
                                        return index;
                                    })
                                    if (flag) {//已在记录中
                                        arr.splice(index, 1);
                                        arr.slice(0, index).forEach(item => {
                                            item.key = (parseInt(item.key, 10) + 1).toString();
                                        })
                                        arr.unshift({ name: fu2, key: "0" })
                                    } else {//不再记录中
                                        arr.forEach(item => {
                                            item.key = (parseInt(item.key, 10) + 1).toString();
                                        })
                                        arr.unshift({ name: fu2, key: "0" });
                                        if (arr.length > 5) {
                                            arr.pop();
                                        }
                                    }
                                }
                                Tools.ss.set("wfAgentListData", arr)
                                searchPage.list.setState({ data: arr })
                            }
                        }}
                    />
                </div>
                {this.getTabDom()}
            </div>
            {this.getDisplayCom()}
            {loading && <ActivityIndicator
                toast
                text={getLabel(500408, "加载中...")}
                animating={loading}
            />}

        </div >
    }
}
export default AddList;